﻿package android;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sms.sms_vs_jok.CatList;

import com.androidquery.util.AQUtility;
 
import sms.sms_vs_jok.R;
 

import android.R.string;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.util.Xml.Encoding;
import android.view.Menu;
import android.view.MenuItem;

public class common extends Application {
	public static String tjkey = "a03b992fd0";
	public static String PublishId = "dfa7cce956a74229b0dbd7044ebdc440";
	public static HashMap<String, HashMap<String, String>> hashMap = new HashMap<String, HashMap<String, String>>();
	private static List<Activity> activityList=new ArrayList<Activity>();
	
	public static HashMap<String, HashMap<String, String>> Gjson(String txt)
			throws JSONException {

		JSONArray jsarray = new JSONArray(txt);
		for (int i = 0; i < jsarray.length(); i++) {
			JSONObject jsonObj = ((JSONObject) jsarray.opt(i));
			String tag = jsonObj.getString("tag");
			if(!hashMap.containsKey(tag))
			{
			JSONObject list = jsonObj.getJSONObject("list");
			Iterator<String> keys = list.keys();
			HashMap<String, String> hashlist = new HashMap<String, String>();
			while (keys.hasNext()) {
				String key = (String) keys.next();
				String value = list.getString(key);
				hashlist.put(key, value);			
			}
			hashMap.put(tag, hashlist);
			}
		}
		return hashMap;
	}

	public static String getFromAsset(Context context, String fileName) {
		String result = "";
		try {
			InputStream in = context.getResources().getAssets().open(fileName);
			int length = in.available();
			byte[] buffer = new byte[length];
			in.read(buffer);
			result = EncodingUtils.getString(buffer, Encoding.UTF_8.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static byte[] desCrypto(byte[] datasource, String password) {
		try {
			SecureRandom random = new SecureRandom();
			DESKeySpec desKey = new DESKeySpec(password.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
			return cipher.doFinal(datasource);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] desdecrypt(byte[] src, String password)
			throws Exception {

		SecureRandom random = new SecureRandom();

		DESKeySpec desKey = new DESKeySpec(password.getBytes());

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

		SecretKey securekey = keyFactory.generateSecret(desKey);

		Cipher cipher = Cipher.getInstance("DES");

		cipher.init(Cipher.DECRYPT_MODE, securekey, random);

		return cipher.doFinal(src);
	}

	public static String encrypt(String seed, String cleartext)
			throws Exception {
		byte[] rawKey = getRawKey(seed.getBytes());
		byte[] result = encrypt(rawKey, cleartext.getBytes());
		return toHex(result);
	}

	public static String decrypt(String seed, String encrypted)
			throws Exception {
		byte[] rawKey = getRawKey(seed.getBytes());
		byte[] enc = toByte(encrypted);
		byte[] result = decrypt(rawKey, enc);
		return new String(result);
	}

	private static byte[] getRawKey(byte[] seed) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
		sr.setSeed(seed);
		kgen.init(128, sr); // 192 and 256 bits may not be available
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		return raw;
	}

	private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(clear);
		return encrypted;
	}

	private static byte[] decrypt(byte[] raw, byte[] encrypted)
			throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] decrypted = cipher.doFinal(encrypted);
		return decrypted;
	}

	public static String toHex(String txt) {
		return toHex(txt.getBytes());
	}

	public static String fromHex(String hex) {
		return new String(toByte(hex));
	}

	public static byte[] toByte(String hexString) {
		int len = hexString.length() / 2;
		byte[] result = new byte[len];
		for (int i = 0; i < len; i++)
			result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
					16).byteValue();
		return result;
	}

	public static String toHex(byte[] buf) {
		if (buf == null)
			return "";
		StringBuffer result = new StringBuffer(2 * buf.length);
		for (int i = 0; i < buf.length; i++) {
			appendHex(result, buf[i]);
		}
		return result.toString();
	}

	private final static String HEX = "0123456789ABCDEF";

	private static void appendHex(StringBuffer sb, byte b) {
		sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
	}

	public static void Init(Activity activity) {
		String url = AQUtility.getTempDir() + "/x";
		File fs = new File(url);
		String x = "";
		if (fs.exists()) {
			x = ReadSDFile(url);
			Log.e("file_txt", "file exist");
		} else {

			x = android.common.getFromAsset(activity, "x");
			try {
				x = android.common.decrypt("sms_vs_jok", x);
				AQUtility.write(fs, x.getBytes());
			} catch (Exception e) {
				Log.e("error_write", e.getMessage());
			}
			
		}

		try {
			android.common.Gjson(x);
		} catch (Exception e) {
            Log.e("error_parse", e.getMessage());
		}

	}

	public static String ReadSDFile(String path) {
		String res = "";
		try {
			FileInputStream fin = new FileInputStream(path);
			int length = fin.available();
			byte[] buffer = new byte[length];
			fin.read(buffer);
			res = EncodingUtils.getString(buffer, "UTF-8");
			fin.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	public static String GetTagList()
	{		
		String tag = "";
		return tag;
	}
	
	public static int GetDrawableByName(String drawablename)
	{
		 Class<R.drawable> cls = R.drawable.class;
		 int value=R.drawable.qingren_jie;
		 try {
			value = cls.getDeclaredField(drawablename).getInt(null);		  
		} catch (Exception e) {
			 
		}  
		return  value;
		 
	}
	

	public static Menu CreateMenu(Activity activity,Menu menu)
	{
		activity.getMenuInflater().inflate(R.menu.menu, menu);
		return menu;
	}
	
	public static boolean MenuSelectItem(Activity activity,MenuItem item)
	{
		boolean status = true;
		
		switch (item.getItemId()) {
		
		 
		case R.id.logout: {
			common.exit();
		}
			break;
		case R.id.home: {
			common.GoActivity(activity, CatList.class);
		}
		 
		}
		
		
		return status;
	}
	

	// 添加Activity到容器中
	public static void addActivity(Activity activity) {
		activityList.add(activity);
	}

	// 遍历所有Activity并finish
	public static void exit() {
		for (Activity activity : activityList) {
			if (activity != null) {
				activity.finish();
			}
		}
		System.exit(0);
	}
	

	public static void GoActivity(Context context, Class<?> activityclass)
	{
		 Intent intent=new Intent();
		 intent.setClass(context,activityclass);
		 intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		 context.startActivity(intent);
	}

}
